use axum::Json;
use serde_json::Value;
use ring::{rand, rsa, signature, digest};


use crate::{base64, code, file};

// fn sign_and_verify_rsa(private_key_path: &str, public_key_path: &str) -> Result<(), MyError> {

//     let private_key_der = get_key(private_key_path)?;
//     let key_pair = rsa::KeyPair::from_der(&private_key_der).map_err(|_| MyError::BadPrivateKey)?;

//     const MESSAGE: &'static [u8] = b"hello, world";

//     let rng = rand::SystemRandom::new();
//     let mut signature = vec![0; key_pair.public().modulus_len()];
//     key_pair.sign(&signature::RSA_PKCS1_SHA256, &rng, MESSAGE, &mut signature).map_err(|_| MyError::OOM)?;

//     // Verify the signature.
//     let public_key = signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, get_key(public_key_path)?);
//     public_key.verify(MESSAGE, &signature).map_err(|_| MyError::BadSignature)
// }

pub async fn sign_sha256_rsa(data:&str, private_key_path: &str) -> Result<String, Json<Value>> {

    // let key_per = get_key(private_key_path).await?;
    let key_per = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrnUe/u3zafOyou/Q4oeRjyUqJEn40kL7Y1g6vuBReiCA0c7hGaGPl/VUI4cSKKrVHjurGXeznPbnK9ivnWx1BlK/e7Ui4+OF5pa0xeEvlTQZa0NFoYEHLs/uulbxOiGNNkAIzTA0EqrkHTtP+Y6flRmf/BMqLE1V4s+MAWGcdJVqdKMS0g/Ut2DWnqP1wpIaUhIIKeHA/QCNBA3RQqnW751YL/5HpV14PTMhJRk4JALI6duy7iGQrPFRSVSu7Br/0mCy4ESTRBKwK4uhinSUnWlbPEHEB/H3XEmIkjnXjLQZLSYnvi3CACPLQLc4ZHvqLYa/Q7yhM00o6WO9SmwP3AgMBAAECggEAdto6cqMaWQbjsAhbn00fq6wgnsXb+fO0+N9m1HOcR8vm4eyy1rA9X28PkVMqlrX1TlXAaxlplMy++715soT7wguDsdSL5O8Y2PLQ+83gYjHyELtGDA9+AeHokITLIWh7vZ/apkQpT+4crt79GtVR1gvowklD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("{}", key_per);

    let encode = digest::digest(&digest::SHA256, data.as_bytes());
    
    let key_pair = rsa::KeyPair::from_der(key_per.as_bytes());
    
    if let Ok(f) = key_pair {
        let rng = rand::SystemRandom::new();
        let mut signature = vec![0; f.public().modulus_len()];
        let sign = f.sign(&signature::RSA_PKCS1_SHA256, &rng, data.as_bytes(), &mut signature);
        if sign.is_ok() {
            Ok(base64::encode(signature))
        }else{
            Err(code::sys_("签名失败"))
        }
    }else{
        Err(code::sys_("加密失败"))
    }
}

async fn get_key(path: &str) -> Result<String, Json<Value>> {
    let key = file::create::open_file_read_to_str(path).await?;
    let key = key
    .replace("-----BEGIN PRIVATE KEY-----", "")
    .replace("-----END PRIVATE KEY-----", "")
    // .replace("-----BEGIN CERTIFICATE-----", "")
    // .replace("-----END CERTIFICATE-----", "")
    .replace("\n", "");
    Ok(key)
}